// facility/mapAudio/mapAudio.js
let tcp;
let recorderManager = wx.getRecorderManager();
let bol = false
let FormData = require('../../components/formData/formData.js')
let audioCtx;
import http from '../../http'
Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		infoType: '',
		nowProjectInfo: '',
		nowfacilityInfo: '',
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		// 播报
		audioBol: false,
		snList: [],
		token: '',
		recordStatus: 0,

		audio: {},
		maxTime: 100,
		nowTime: 0,
		nowTimeText: '00:00',
		playerStatus: 0,
		// 音量
		volumeBol: false,
		volume: 50,
		// 定时任务
		timingBol: false,
		timingList: [],
		// 激活
		activateBol: false,
		sqr: ''
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		start(value) {
			wx.showLoading({
				title: '加载中...'
			});
			var formData = new FormData();
			formData.append("username", "wzn");
			formData.append("passwd", "wzn123456");
			let newData = formData.getData();
			http.post({
				prefix: '/xxbs',
				url: "/user/gtoken",
				header: {
					'content-type': newData.contentType
				},
				data: newData.buffer,
				then: (res) => {
					console.log('音柱登录', res);
					this.setData({
						token: res.data.token
					})
					// 组控
					if (this.properties.infoType == 'project') {
						let data = {
							pageNo: 1,
							pageSize: -1,
							categoryId: "Audio",
						}
						if (this.properties.nowProjectInfo.type == 0) {
							data.projectId = this.properties.nowProjectInfo.id
						} else {
							data.group = this.properties.nowProjectInfo.id
						}
						http.get({
							url: '/zg/device-instance/page',
							data: data,
							then: (res) => {
								console.log('音柱列表', res);
								let snList = res.data.data.list.map(item => {
									return item.sn
								})
								this.setData({
									snList: snList,
								}, () => {
									if (this.data.snList.length == 0) {
										wx.showToast({
											title: '该项目下没有音柱',
											icon: 'error',
										})
									} else {
										wx.hideLoading()
										if (value == 'broadcast') {
											this.setData({
												audioBol: true
											})
											this.recordEvent() // 录音机监听函数
										} else if (value == 'volume') {
											this.setData({
												volumeBol: true
											})
										} else if (value == 'timing') {
											this.setData({
												timingBol: true,
											})
											this.timingGain()
										}
									}
								});
							}
						})
					} else {
						// 单控
						http.get({
							url: '/zg/device-instance/get',
							data: {
								id: this.properties.nowfacilityInfo.id
							},
							then: (res) => {
								console.log('音柱信息', res);
								this.setData({
									snList: [res.data.data.sn]
								}, () => {
									wx.hideLoading()
									if (value == 'broadcast') {
										this.setData({
											audioBol: true
										})
										this.recordEvent() // 录音机监听函数
									} else if (value == 'volume') {
										this.setData({
											volumeBol: true
										})
									} else if (value == 'timing') {
										this.setData({
											timingBol: true
										})
										this.timingGain()
									}
								});
							}
						})
					}
				}
			})
		},
		tcpLink() {
			let formData = {
				Meport: 23202, //跨服端口号
				Umagic: 89686, //快服句柄随机数
				userid: 1, //userid 用户id
				token: this.data.token, //用户token
				Umask: "84d3def493da487b96ed12744ad44c7a", //快服填随机字符串
				plevel: 9, //该用户内播放等级1~9 9是最高优先级 
				ulevel: 600, //用户间等级 1~600   不同用户间同时推流一个音响 等级高的会切掉等级低的
				snlist: this.data.snList, //被播放的设备序列号
				cmd: "PLAYLIST", //固定值
				Meip: http.ip // 您的节点服务器IP地址 
			}
			let userInfo = JSON.stringify(formData).length + "\n" + JSON.stringify(formData);
			tcp = wx.createTCPSocket()
			tcp.connect({
				// address: '81.70.48.111',
				address: http.ip,
				port: '6002'
			})
			// 连接成功
			tcp.onConnect((e) => {
				console.log('TCP连接成功')
				tcp.write(userInfo);
			});
			// 接收消息
			tcp.onMessage((e) => {
				console.log('接收消息', e);
				//ArrayBuffer转16进制字符串
				let buffer = e.message
				let hexstr = Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
				console.log(hexstr);
				// 连接音柱成功
				if (hexstr == "57454c4c") {
					console.log('连接音柱成功,通信中...');
					bol = true;
					var obj = {
						duration: 600000,
						sampleRate: 44100,
						encodeBitRate: 64000,
						format: "mp3",
						frameSize: '1'
					}
					recorderManager.start(obj);
					wx.hideLoading()
					this.setData({
						recordStatus: 1
					})
				} else {
					console.log('连接音柱失败.检查网络ER02",2000');
					wx.showToast({
						title: '请检查网络',
						icon: 'error',
					})
					bol = false;
					// 结束播报
					this.startOrEndRecord()
				}
			});
			// 连接关闭
			tcp.onClose((res) => {
				console.log('连接关闭：' + JSON.stringify(res));
				console.log('通信结束', 2000);
				bol = false;
			});
			// 连接失败
			tcp.onError((res) => {
				console.log('连接失败：' + JSON.stringify(res));
				console.log("通信异常结束", 2000);
				wx.showToast({
					title: '连接失败',
					icon: 'error',
				})
				bol = false;
				tcp.close();
			});
			// 离线
			tcp.offConnect((res) => {
				console.log('离线：' + res);
				console.log("通信结束", 2000);
				wx.showToast({
					title: '离线',
					icon: 'error',
				});
				bol = false;
				tcp.close();
			});
		},
		// 录音回调事件
		recordEvent() {
			// 录音停止事件
			recorderManager.onStop((res) => {
				console.log('录音停止' + JSON.stringify(res));
				audioCtx = wx.createInnerAudioContext({})
				audioCtx.src = res.tempFilePath
				this.setData({
					nowTimeText: res.duration / 1000 / 60 >= 1 ? Math.floor(res.duration / 1000 / 60).toString().padStart(2, "0") + ':' + Math.floor(res.duration / 1000 % 60).toString().padStart(2, "0") : '00:' + Math.floor(res.duration / 1000).toString().padStart(2, "0"),
					audio: res
				})
				this.playerEvent()
			})
			// 已录制完指定帧大小的文件
			recorderManager.onFrameRecorded((res) => {
				if (bol) {
					if (res.isLastFrame) {
						console.log('完成录制' + JSON.stringify(res));
						tcp.write(res.frameBuffer);
						setTimeout(() => {
							tcp.close();
						}, 1000);
					} else {
						console.log('录制中...' + JSON.stringify(res));
						tcp.write(res.frameBuffer)
					}
				}
			});
		},

		// 播报开关
		startOrEndRecord() {
			// 开始播报
			if (this.data.recordStatus == 0) {
				wx.showLoading({
					title: '加载中...'
				});
				this.tcpLink()
			} else {
				// 结束播报
				recorderManager.stop();
				this.setData({
					recordStatus: 0
				})
			}
		},
		// 音频播放器事件
		playerEvent() {
			let time;
			// 监听音频进入可以播放状态的事件
			audioCtx.onCanplay(() => {

			})
			// 监听音频播放事件
			audioCtx.onPlay(() => {
				this.setData({
					playerStatus: 1,
				})
				time = setInterval(() => {
					// console.log(audioCtx);
					this.setData({
						maxTime: audioCtx.duration,
						nowTime: audioCtx.currentTime,
						nowTimeText: audioCtx.currentTime / 60 >= 1 ? Math.floor(audioCtx.currentTime / 60).toString().padStart(2, "0") + ':' + Math.floor(audioCtx.currentTime % 60).toString().padStart(2, "0") : '00:' + Math.floor(audioCtx.currentTime).toString().padStart(2, "0")
					})
				}, 100);
			})
			// 监听音频停止事件
			audioCtx.onStop(() => {
				clearInterval(time)
				this.setData({
					playerStatus: 0,
					nowTime: this.data.maxTime,
					nowTimeText: this.data.audio.duration / 1000 / 60 >= 1 ? Math.floor(this.data.audio.duration / 1000 / 60).toString().padStart(2, "0") + ':' + Math.floor(this.data.audio.duration / 1000 % 60).toString().padStart(2, "0") : '00:' + Math.floor(this.data.audio.duration / 1000).toString().padStart(2, "0")
				})
			})
			// 监听音频自然播放至结束的事件
			audioCtx.onEnded(() => {
				this.setData({
					playerStatus: 0,
					nowTime: this.data.maxTime
				})
				clearInterval(time)
			})
		},
		// 音频播放器开关
		startOrEndPlayer() {
			// 开始播放
			if (this.data.playerStatus == 0) {
				audioCtx.play() // 播放
			} else {
				// 结束播放
				audioCtx.stop() // 停止
			}
		},
		// 播报
		broadcast() {
			this.start('broadcast')
		},
		audioClose() {
			if (audioCtx) {
				audioCtx.destroy()
			}
			if (this.data.recordStatus == 1) {
				// 结束播报
				recorderManager.stop();
				this.setData({
					recordStatus: 0
				})
			}
			this.setData({
				audioBol: false,
				recordStatus: 0
			})
		},
		// 音量
		volumeBtn() {
			this.start('volume')
		},
		volumeClose() {
			this.setData({
				volumeBol: false
			})
		},
		volumeControl() {
			wx.showLoading({
				title: '加载中...'
			});
			var formData = new FormData();
			formData.append("id", 1);
			formData.append("token", this.data.token);
			formData.append("snlist", this.data.snList.join('|'));
			formData.append("vol", Math.round(this.data.volume * 0.63));
			let newData = formData.getData();
			http.post({
				prefix: '/xxbs',
				url: "/user/editvols",
				header: {
					'content-type': newData.contentType
				},
				data: newData.buffer,
				then: (res) => {
					console.log('控制音量', res);
					if (res.data.res) {
						wx.showToast({
							title: '下发成功',
							icon: 'success',
						})
					} else {
						wx.showToast({
							title: res.data.info,
							icon: 'error',
						})
					}
				}
			})
		},
		volumeChange(event) {
			this.setData({
				volume: event.detail
			}, () => {
				this.volumeControl()
			})
		},
		volumeChange1(event) {
			this.setData({
				volume: event.detail.value
			})
		},
		// 定时任务
		timingBtn() {
			this.start('timing')
		},
		timingGain() {
			var formData = new FormData();
			formData.append("id", "1");
			formData.append("token", this.data.token);
			let newData = formData.getData();
			http.post({
				prefix: '/xxbs',
				url: "/user/list_task",
				method: "post",
				header: {
					'content-type': newData.contentType
				},
				data: newData.buffer,
				then: (res) => {
					console.log('定时任务列表', res);
					this.setData({
						timingList: res.data.taskary
					})
				}
			})
		},
		timingSwitch(event) {
			wx.showLoading({
				title: '下发中...'
			});
			console.log(event);
			let taskId = event.currentTarget.dataset.taskid
			let url = ''
			if (event.detail) {
				url = '/user/enabletask'
			} else {
				url = '/user/disabletask'
			}
			var formData = new FormData();
			formData.append("id", "1");
			formData.append("token", this.data.token);
			formData.append("taskid", taskId);
			let newData = formData.getData();
			http.post({
				prefix: '/xxbs',
				url: url,
				header: {
					'content-type': newData.contentType
				},
				data: newData.buffer,
				then: (res) => {
					console.log('启用(禁用)任务', res);
					let list = this.data.timingList
					list.forEach(item => {
						if (item.id == taskId) {
							event.detail ? item.enable = 1 : item.enable = 0
						}
					})
					this.setData({
						timingList: list
					})
					wx.showToast({
						title: '下发成功',
						icon: 'success',
					})
				}
			})
		},
		timingIssue(event) {
			console.log(event.currentTarget.dataset.taskid);
			var formData = new FormData();
			formData.append("id", "1");
			formData.append("token", this.data.token);
			formData.append("taskid", event.currentTarget.dataset.taskid);
			formData.append("snids", this.data.snList.join('|'));
			let newData = formData.getData();
			http.post({
				prefix: '/xxbs',
				url: "/user/editsns_task",
				header: {
					'content-type': newData.contentType
				},
				data: newData.buffer,
				then: (res) => {
					console.log('修改下发设备', res);
				}
			})
		},
		timingClose() {
			this.setData({
				timingBol: false
			})
		},
		// 激活
		activate() {
			wx.showLoading({
				title: '加载中...'
			});
			http.get({
				url: '/zg/device-instance/get',
				data: {
					id: this.properties.nowfacilityInfo.id
				},
				then: (res) => {
					console.log('设备信息', res);
					this.setData({
						form: res.data.data
					})
					if (res.data.data.deviceMetadata) {
						let form = {
							name: res.data.data.name,
							sn: res.data.data.sn,
							deviceMetadata: res.data.data.deviceMetadata,
							productId: res.data.data.productId,
							lightId: res.data.data.lightId,
							labelId: res.data.data.labelId,
							parentId: res.data.data.parentId,
							remarks: res.data.data.remarks,
							status: res.data.data.status,
						}
						for (const key in form) {
							if (form[key] != 0 && !form[key]) {
								delete form[key]
							}
						}
						http.post({
							url: '/zg/audio/deviceadd',
							data: form,
							then: (res) => {
								console.log('灯杆添加设备(音柱)', res);
								if (res.data.code == 0) {
									wx.showToast({
										title: '激活成功',
										icon: 'success',
									})
								}
							}
						})
					} else {
						this.setData({
							activateBol: true
						})
						wx.hideLoading()
					}
				}
			})
		},
		sqrScan() {
			wx.scanCode({
				scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'],
				success: (res) => {
					console.log('二维码数据', res)
					this.setData({
						sqr: res.result
					})
				}
			})
		},
		activateConfirm() {
			let form = {
				name: this.data.form.name,
				sn: this.data.form.sn,
				deviceMetadata: this.data.sqr,
				productId: this.data.form.productId,
				lightId: this.data.form.lightId,
				labelId: this.data.form.labelId,
				parentId: this.data.form.parentId,
				remarks: this.data.form.remarks,
				status: this.data.form.status,
			}
			for (const key in form) {
				if (form[key] != 0 && !form[key]) {
					delete form[key]
				}
			}
			http.post({
				url: '/zg/audio/deviceadd',
				data: form,
				then: (res) => {
					console.log('灯杆添加设备(音柱)', res);
					if (res.data.code == 0) {
						wx.showToast({
							title: '激活成功',
							icon: 'success',
						})
					}
				}
			})
		},
		activateClose() {
			this.setData({
				activateBol: false
			})
		}
	},
	pageLifetimes: {
		hide() {
			if (this.data.recordStatus == 1) {
				// 结束播报
				recorderManager.stop();
				this.setData({
					recordStatus: 0
				})
			}
		}
	}
})